package com.guapi.service;

import cn.hutool.core.util.StrUtil;
import com.guapi.dao.Conversation;
import com.guapi.util.BaseConstant;
import com.guapi.util.ConversationConstant;
import org.springframework.stereotype.Service;

import java.util.*;

@Service
public class ConversationService extends SelfBaseService<Conversation> implements BaseConstant, ConversationConstant {

    public void sendConversation(Map dataMap, Integer fromId, Integer toId) {
        String content = (String) dataMap.get("content");
        String thisConversationId = fromId + DOWN_LINE + toId;
        Conversation conversation = new Conversation();
        conversation.setContent(content);
        conversation.setToId(toId);
        conversation.setFromId(fromId);
        conversation.setConversationId(thisConversationId);
        if (fromId == 0) {
            conversation.setType(SYSTEM_MESSAGE);
        } else {
            conversation.setType(USER_MESSAGE);
        }
        conversation.setCreateBy(String.valueOf(fromId));
        conversation.setStatus(0);
        this.save(conversation);
        //发送新消息，默认旧消息已读，将同一会话Id的会话状态设为已读
        this.setConversationRead(StrUtil.reverse(thisConversationId));
    }

    public List<List<Conversation>> packageConversation(List<Conversation> conversations) {

        HashMap<String, List<Conversation>> map = new HashMap<>();
        for (Conversation con : conversations) {
            String conversationId = con.getConversationId();
            String[] ids = conversationId.split("_");
            Arrays.sort(ids);
            conversationId = String.join("_", ids);
            if (map.containsKey(con.getConversationId()) || map.containsKey(StrUtil.reverse(con.getConversationId()))) {
                List<Conversation> groupList = map.get(conversationId);
                groupList.add(con);
            } else {
                ArrayList<Conversation> tmpConversationList = new ArrayList<>();
                tmpConversationList.add(con);
                map.put(conversationId, tmpConversationList);
            }
        }

        return new ArrayList<>(map.values());
    }

    public void setConversationRead(Integer fromId, Integer toId) {
        Conversation conversation = new Conversation();
        conversation.setFromId(fromId);
        conversation.setToId(toId);
        conversation.setStatus(1);
        this.saveOrUpdate(conversation);
    }

    public void setConversationRead(String conversationId) {
        Conversation conversation = new Conversation();
        conversation.setConversationId(conversationId);
        List<Conversation> conditions = this.getByConditions(conversation);
        conditions.forEach(item -> {
            item.setStatus(1);
            this.updateById(item);
        });
    }
}
